package com.stylefeng.guns.modular.huamao.controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
//import com.baomidou.mybatisplus.plugins.pagination.PageHelper;
import com.github.pagehelper.PageHelper;
import com.stylefeng.guns.core.base.controller.BaseController;
import com.stylefeng.guns.core.util.MD5Util;
import com.stylefeng.guns.modular.huamao.model.*;
import com.stylefeng.guns.modular.huamao.result.AppResult;
import com.stylefeng.guns.modular.huamao.service.*;
import com.stylefeng.guns.modular.huamao.service.impl.ATestServiceImpl;
import com.stylefeng.guns.modular.huamao.service.impl.OptBingServiceImpl;
import com.stylefeng.guns.modular.huamao.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.util.*;
@CrossOrigin
@SuppressWarnings("all")
@Controller
@RequestMapping("/app")
public class AppAccountController extends BaseController{

    @Autowired
    private IAppAccountService appAccountService;
    @Autowired
    private IAppLogCashService applogCashService;
    @Autowired
    private IAppLogCashFreezeService appLogCashFreezeService;
    @Autowired
    private IAppUserService iAppUserService;
    @Autowired
    private IAppDateTransformService iAppDateTransformService;
    @Autowired
    private IAppLogKaiyuanService iAppLogKaiyuanService;
    @Autowired
    private IAppLogKaiyuanTurnoverService iAppLogKaiyuanTurnoverService;
    @Autowired
    private IAppUsersUpgradeService iAppUsersUpgradeService;
    @Autowired
    private IAppAccountService iAppAccountService;
    @Autowired
    private IAppAccountShopService iAppAccountShopService;
    @Autowired
    private CacheUtil cacheUtil;
    @Autowired
    private IUsersUpgradeService  usersUpgradeService;
    @Autowired
    private IAccountService accountService;
    @Autowired
    private IShoppingService  shoppingService;
    @Autowired
    private IUsersService usersService;
    @Autowired
    private  ATestServiceImpl aTestService;
    @Autowired
    private IUsersRechargeService usersRechargeService;
    @Autowired
    private IAppUserDrwasService iAppUserDrwasService;
    @Autowired
    private IAppUsersRechargeService iAppUsersRechargeService;
    @Autowired
    private IAppUserDrwasMaobiService iAppUserDrwasMaobiService;
    @Autowired
    private IOptBingService iOptBingService;


    /**
     * 我的账户
     * @return
     */
    @RequestMapping("/Account/myAccount")
    @ResponseBody
    public AppResult accountMyAccount(){
        try {
            Account accounts=new Account();
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            if (user==null){
                return AppResult.ERROR("请先登录",-1);
            }
            Account account = appAccountService.selectAccountByUserId(user.getUserId());
            Map<String,Object> map=new HashMap<String,Object>();
            map.put("userId", account.getUserId());
            map.put("cash", String.valueOf(account.getCash()));
            map.put("freezeCash", String.valueOf(account.getFreezeCash()));
            return AppResult.OK("查询成功",map);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("您还未登陆",-2);
        }
    }


    /**
     * 提现进度
     * @param pageIndex
     * @return
     */
    @RequestMapping("/Account/presentProgress")
    @ResponseBody
    public AppResult AccountPresentProgress(@ModelAttribute("pageIndex")String pageIndex,@ModelAttribute("type")String type){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            PageHelper.startPage(Integer.valueOf(pageIndex),15);
            Map<String, Object> map = new HashMap<>();
            map.put("userId",user.getUserId());
            map.put("type",MSGUtil.isBlank(type)?2:Integer.parseInt(type));
            List<UsersDraws> usersDrawsList=appAccountService.presentProgress(map);
            List<Object> objects = new ArrayList<>();
            for (UsersDraws usersDraws:usersDrawsList) {
                Map<String, Object> map1 = new HashMap<>();
                map1.put("money",usersDraws.getMoney().toString());
                map1.put("drawNo",usersDraws.getDrawNo());
                map1.put("cashSatus",usersDraws.getCashSatus());
                map1.put("createTime",usersDraws.getCreateTime());
                map1.put("getTime",usersDraws.getGetTime());
                objects.add(map1);
            }
            return AppResult.OK("查询成功",objects);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("查询失败",-1);
        }
    }

    /**
     * 现金记录
     * @param pageIndex
     * @return
     */
    @RequestMapping("/Account/cashRecord")
    @ResponseBody
    public AppResult AccountCashRecord(@ModelAttribute("pageIndex") String pageIndex){
        try {
            if(!cacheUtil.isKeyInCache(SessionUtils.getSessionId())){
                return AppResult.ERROR("您还未登陆",-2);
            }
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            LogCash logCash=new LogCash();
            logCash.setUserId(user.getUserId());
            Integer pageNum=Integer.parseInt(pageIndex);
            AppResult appResult=applogCashService.AccountCashRecord(pageNum,logCash);
            return appResult;
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("获取失败",-1);
        }
    }

    /**
     * 猫币或hhtb记录
     * @param pageIndex
     * @return
     */
    @RequestMapping("/Account/maobiRecord")
    @ResponseBody
    public AppResult AccountMaobiRecord(@ModelAttribute("pageIndex") String pageIndex,@ModelAttribute("type")String type){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            UsersDrawsMaobi usersDrawsMaobi=new UsersDrawsMaobi();
            usersDrawsMaobi.setUserId(user.getUserId());
            usersDrawsMaobi.setType(Integer.parseInt(type));
            Integer pageNum=Integer.parseInt(pageIndex);
            AppResult appResult=iAppUserDrwasMaobiService.AccountMaobiRecord(pageNum,usersDrawsMaobi);
            return appResult;
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("您还未登陆",-1);
        }
    }


    /**
     * 代发现金记录
     * @return
     */
    @RequestMapping("/Account/willCashRecord")
    @ResponseBody
    public AppResult AccountWillCashRecord(@ModelAttribute("pageIndex")String pageIndex){
        try {
            Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
            if (user == null) {
                user.setUserId(0);
            }
            PageHelper.startPage(Integer.valueOf(pageIndex), 15);
            List<LogCashFreeze> logCashFreezes = appLogCashFreezeService.AccountWillCashRecord(user.getUserId());
            List<Object> list = new ArrayList<>();
            if (logCashFreezes.size() > 0) {
                for (LogCashFreeze logCash1 : logCashFreezes) {
                    Map<String, Object> map = new HashMap<>();
                    map.put("orderNo", logCash1.getOrderNo());
                    map.put("cash", logCash1.getCash().toString());
                    map.put("cashType", logCash1.getCashType());
                    TradeDictDTD tradeDictDTD=appLogCashFreezeService.selectTradeDictByType(logCash1.getCashType());
                    map.put("type", tradeDictDTD.gettName());
                    map.put("createTime", logCash1.getCreateTime());
                    list.add(map);
                }
            }
            return AppResult.OK("获取成功", list);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("获取失败",-1);
        }
    }

    /**
     * 修改用户头像
     * @param userPhoto
     * @return
     */
    @RequestMapping("/account/changeImage")
    @ResponseBody
    public AppResult changeImage(@ModelAttribute("userPhoto")String userPhoto){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            user.setUserPhoto(userPhoto);
            boolean userMsg = iAppUserService.updateById(user);
            if(!userMsg){
                return AppResult.ERROR("修改失败",-1);
            }
            return AppResult.OK("修改成功",null);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("未登录",-2);
        }
    }

    /**
     * 我的华宝
     * @return
     */
    @RequestMapping("/account/myHuaBao")
    @ResponseBody
    public AppResult myHuaBao(){
        Map<String, Object> map = new HashMap<>();
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            if (user==null){
                return AppResult.ERROR("请先登录",-2);
            }
            MyAccountHuabao myhuabao=appAccountService.myHuaBao(user.getUserId());
            List<SktDateTransform> date=iAppDateTransformService.selectDateTransform();
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("isStore",myhuabao.getIsStore());
            map1.put("isShop",myhuabao.getIsShop());
            map1.put("kaiyuan",myhuabao.getKaiyuan().toString());
            map1.put("kaiyuanTurnover",MSGUtil.isBlank(myhuabao.getKaiyuanTurnover())?"0.00":myhuabao.getKaiyuanTurnover().toString());
            map1.put("freezeKaiyuan",MSGUtil.isBlank(myhuabao.getFreezeKaiyuan())?"0.00":myhuabao.getFreezeKaiyuan().toString());
            List<Object> objects = new ArrayList<>();
            for (SktDateTransform sktDateTransform:date){
                Map<String, Object> map2 = new HashMap<>();
                map2.put("date",sktDateTransform.getDate());
                map2.put("ratio",sktDateTransform.getRatio().toString());
                objects.add(map2);
            }
            map.put("account",map1);
            map.put("dateTransform",objects);
            return AppResult.OK("查询成功",map);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("请先登录",-2);
        }
    }

    /**
     * 华宝记录
     * @return
     */
    @RequestMapping("/account/huaBaoList")
    @ResponseBody
    public  AppResult huaBaoList(){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            if(user==null){
              return AppResult.ERROR("您未登录",-2);
            }
            List<LogKaiyuan> logKaiyuanList=iAppLogKaiyuanService.huaBaoList(user.getUserId());
            List<Object> list = new ArrayList<>();
            Map<String, Object> mapList = new HashMap<>();
            mapList.put("gType","log_kaiyuan");
            for (LogKaiyuan logKaiyuan:logKaiyuanList) {
                mapList.put("tCode",String.valueOf(logKaiyuan.getType()));
                Map<String, Object> maps = new HashMap<>();
                TradeDictDTD tradeDictDTD=iAppLogKaiyuanService.selectTradeDict(mapList);
                maps.put("type",tradeDictDTD.gettName());
                maps.put("orderNo",logKaiyuan.getOrderNo());
                maps.put("kaiyuanType",logKaiyuan.getKaiyuanType());
                maps.put("kaiyuan",logKaiyuan.getKaiyuan());
                maps.put("remark",logKaiyuan.getRemark());
                maps.put("createTime",logKaiyuan.getCreateTime());
                list.add(maps);
            }
            return AppResult.OK("查询成功",list);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("查询错误",-1);
        }
    }

    /**
     * 华宝货款记录
     * @return
     */
    @RequestMapping("/account/huaBaoTurnoverList")
    @ResponseBody
    public  AppResult huaBaoTurnoverList(){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            List<LogKaiyuanTurnover> logKaiyuanTurnoverList=iAppLogKaiyuanTurnoverService.huaBaoTurnoverList(user.getUserId());
            List<Object> list = new ArrayList<>();
            Map<String, Object> mapList = new HashMap<>();
            mapList.put("gType","log_kaiyuan_turnover");
            for (LogKaiyuanTurnover logKaiyuanTurnover:logKaiyuanTurnoverList) {
                mapList.put("tCode",String.valueOf(logKaiyuanTurnover.getType()));
                Map<String, Object> maps = new HashMap<>();
                TradeDictDTD tradeDictDTD=iAppLogKaiyuanService.selectTradeDict(mapList);
                maps.put("type",tradeDictDTD.gettName());
                maps.put("orderNo",logKaiyuanTurnover.getOrderNo());
                maps.put("kaiyuanType",logKaiyuanTurnover.getKaiyuanType());
                maps.put("kaiyuan",logKaiyuanTurnover.getKaiyuan());
                maps.put("remark",logKaiyuanTurnover.getRemark());
                maps.put("createTime",logKaiyuanTurnover.getCreateTime());
                list.add(maps);
            }
            return AppResult.OK("查询成功",list);
        }catch (Exception e){
            e.printStackTrace();
            return AppResult.ERROR("您还未登陆",-2);
        }
    }

    /**
     * 升级(下单)
     * @param userType
     * @param money
     * @return
     */
    @RequestMapping("/account/userUpgrade")
    @ResponseBody
    @Transactional
    public AppResult userUpgrade(@ModelAttribute("userType")String userType,@ModelAttribute("money")String money){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            Map<Object, Object> maps = new HashMap<>();
            maps.put("userId",user.getUserId());
            maps.put("code","userUpgrade");
            boolean insertOptBing=iAppUsersUpgradeService.insertOptBing(maps);
            UsersUpgrade hasApplys = iAppUsersUpgradeService.selectUsersUpgradeByUserId(user.getUserId());
            if (!MSGUtil.isBlank(hasApplys)){
                return AppResult.ERROR("你已提交过申请，正审核中不能继续申请",-1);
            }
            maps.put("status",1);
            Users users=iAppUserService.selectUsersByUserIdAndUserStatus(maps);
            if (MSGUtil.isBlank(users)){
                return AppResult.ERROR("账号不存在或被停用",-1);
            }
            int userTypes = Integer.parseInt(userType);
            double moneys = Double.valueOf(money);
            if (userTypes==1){//升级为主管
                if (users.getUserType()>0){
                    return AppResult.ERROR("该账号已不是普通会员，无需再升级为主管",-1);
                }
                if (moneys!=997){
                    return AppResult.ERROR("支付金额有误",-1);
                }
            }
            if (userTypes==2){//升级为经理
                if (users.getUserType()==2){
                    return AppResult.ERROR("该账号已是经理，无需再升级",-1);
                }else if(users.getUserType()==1){//主管升级为经理
                    if (moneys!=9000){
                        return AppResult.ERROR("支付金额有误",-1);
                    }
                }else if (users.getUserType()==0){
                    if (moneys!=9997){
                        return AppResult.ERROR("支付金额有误",-1);
                    }
                }
            }
            //组装升级申请订单数据
            String orderNo = StringUtils.getOrderIdByTime("3");
            UsersUpgrade usersUpgrade = new UsersUpgrade();
            usersUpgrade.setOrderNo(orderNo);//订单号
            usersUpgrade.setUserId(user.getUserId());
            usersUpgrade.setPreRole(users.getUserType());//升级前角色 0普通 1主管
            usersUpgrade.setAfterRole(userTypes);//升级后角色 1主管 2经理
            usersUpgrade.setTotalMoney(new BigDecimal(moneys));//订单总金额 (realMoney+cash+kaiyuan)
            usersUpgrade.setRealMoney(new BigDecimal(moneys));//实际支付金额 通过支付公司现金支付的金额
            usersUpgrade.setOrderRemarks("用户升级角色"); //订单备注
            usersUpgrade.setCreateTime(new Date());//下单时间
            usersUpgrade.setDataFlag(1); //有效标志 1有效 0删除
            usersUpgrade.setStatus(0);//状态 0未支付 1已付款未处理 2已取消 3已处理
            boolean insert = iAppUsersUpgradeService.insert(usersUpgrade);
            Map<Object, Object> map = new HashMap<>();
            if (insert){
                Account account = iAppAccountService.selectAccountByUserId(user.getUserId());
                AccountShop accountShop=iAppAccountShopService.selectAccountShopByUserId(user.getUserId());
                map.put("cash",account!=null?account.getCash():0.00);
                map.put("kaiyuan",account!=null?account.getKaiyuan():0.00);
                map.put("money",moneys);
                map.put("kaiyuanTurnover",accountShop!=null?accountShop.getKaiyuanTurnover():0.00);
                map.put("orderNo",orderNo);
                iAppUsersUpgradeService.delectOptBingByUserIdAndCode(maps);
                return AppResult.OK("申请升级成功！",map);
            }
            return AppResult.ERROR("申请升级失败",-1);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("失败");
        }
    }

    /**
     * 现金支付
     * @param orderNo  订单号
     * @param payPwd 支付密码
     * @return
     */
    @RequestMapping("/account/buyUpgrade")
    @ResponseBody
    @Transactional
    public AppResult buyUpgrade(@ModelAttribute("orderNo")String orderNo,
                                @ModelAttribute("payPwd")String payPwd ){
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            Map<Object, Object> map = new HashMap<>();
            map.put("userId",user.getUserId());
            map.put("code","buyUpgrade");
            Users users = iAppUserService.selectUsersByUserId(user.getUserId());
            if (users.getUserStatus()!=1){
                return AppResult.ERROR("该账户已经被禁用",-1);
            }
            String encrypt = MD5Util.encrypt(payPwd+users.getLoginSecret());
            if (!MD5Util.encrypt(payPwd+users.getLoginSecret()).equals(users.getPayPwd())){
                return AppResult.ERROR("支付密码输入不正确",-1);
            }
            Account account = iAppAccountService.selectAccountByUserId(users.getUserId());
            map.put("orderNo",orderNo);
            UsersUpgrade usersUpgrade=usersUpgradeService.selectUsersUpgradeByUserIdOrderNo(map);
            if (MSGUtil.isBlank(usersUpgrade)){
                return AppResult.ERROR("该订单不存在",-1);
            }
            if (usersUpgrade.getTotalMoney().doubleValue()>account.getCash().doubleValue()){
                return AppResult.ERROR("你的现金余额不足以本次支付所需",-1);
            }
            if (usersUpgrade.getStatus()==1){
                return AppResult.OK("该订单已经处理成功",null);
            }
            LogCash logCash = new LogCash();
            logCash.setType(35);
            logCash.setFromId(users.getUserId());
            logCash.setUserId(user.getUserId());
            logCash.setOrderNo(orderNo);
            logCash.setPreCash(account.getCash());
            logCash.setCash(usersUpgrade.getTotalMoney());
            logCash.setCashType(-1);
            logCash.setRemark("用户升级现金支付支出");
            logCash.setDataFlag(1);
            logCash.setCreateTime(new Date());
            //插入现金支出流水
            boolean insert = applogCashService.insert(logCash);
            if (!insert){
                return AppResult.ERROR("失败",-1);
            }
            //减少用户支出现金
            Account account1 = new Account();
            account1.setUserId(users.getUserId());
            account1.setCash(account.getCash().subtract(usersUpgrade.getTotalMoney()));
            account1.setAccountId(account.getAccountId());
            boolean b = iAppAccountService.updateById(account1);
            if (!b){
                return AppResult.ERROR("修改失败",-1);
            }
            //支付成功改变订单状态
            UsersUpgrade usersUpgrade1 = new UsersUpgrade();
            usersUpgrade1.setOrderId(usersUpgrade.getOrderId());
            usersUpgrade1.setStatus(1);
            usersUpgrade1.setUpgradeTime(new Date());
            usersUpgrade1.setPayType(2);
            usersUpgrade1.setCash(usersUpgrade.getTotalMoney());
            usersUpgradeService.updateByOrderId(usersUpgrade1);
            Map<Object, Object> map1 = new HashMap<>();
            map1.put("orderNo",orderNo);
            map1.put("totalMoney",usersUpgrade.getTotalMoney());
            map1.put("createTime",new Date());
            return AppResult.OK("支付成功",map1);
        }catch (Exception e){
            e.printStackTrace();
            throw new RuntimeException("失败");
        }

    }

    /**
     * 根据条件查询查找优惠券
     * @param status  优惠券状态
     * @return
     */
    @RequestMapping("/account/myShopping")
    @ResponseBody
    public AppResult myShopping(@ModelAttribute("status")String status,
                                @ModelAttribute("pageIndex")Integer pageIndex  ){
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
     //  Users user=   usersService.selectById(1);
        if (user!=null){
            Map<String,Object> map=new HashMap<>();
            map.put("dataId",user.getUserId());
            map.put("status",status);
            map.put("dataFlag",1);
            PageHelper.startPage(pageIndex,10);
            List<Map<String, Object>> maps = shoppingService.selectShoppingList(map);
            List<Object> objects = new ArrayList<>();
            for (Map<String, Object> shopping:maps){
                shopping.put("money",shopping.get("money").toString());
                objects.add(shopping);
            }
            return    AppResult.OK(objects);
        }else {
            return AppResult.ERROR("您未登录",-2);
        }
    }

    /**
     * 充值(下单)
     * @param cash
     * @return
     */
    @RequestMapping("/Account/RechargeOrder")
    @ResponseBody
    public  AppResult RechargeOrder(@ModelAttribute("cash")BigDecimal cash){
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        //  Users user=   usersService.selectById(1);
        if (user!=null){
            JSONObject json = iAppAccountService.recharge(user.getUserId(), 4, cash, "现金充值", 0);
            return AppResult.OK(json);
        }else {
            return AppResult.ERROR("您未登录",-2);
        }
    }
    /**
     * 点击线下支付
     */
    @RequestMapping("/Account/clickUnderLinePay")
    @ResponseBody
    public AppResult clickUnderLinePay() {
        UnderLinePay underLinePay = accountService.clickUnderLinePay();
        return AppResult.OK(underLinePay);
    }

    /**
     *线下 充值(支付 上传汇款单)
     * @param request
     * @param response
     * @param orderNO
     * @return
     */
    @RequestMapping("/Account/Recharge")
    @ResponseBody
    public AppResult recharge(HttpServletRequest request, HttpServletResponse response,@ModelAttribute("orderNo")String orderNo) {
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if (user!=null){
            Map<String, Object> map = usersRechargeService.Recharge(request, orderNo);
            if ("01".equals(map.get("code").toString())){
                return   AppResult.OK(map.get("msg").toString(),1);
            }else{
                return   AppResult.OK(map.get("msg").toString(),0);
            }
        }else {
            return AppResult.ERROR("您未登录",-2);
        }
    }

    /**
     * 提现(数据回显)
     * @return
     */
    @RequestMapping("/Account/cashDraw")
    @ResponseBody
    public AppResult cashDraw(){
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if (user!=null){
            JSONObject jsonObject = iAppUserDrwasService.cashDraw(user.getUserId());
        return    AppResult.OK(jsonObject);
        }else {
            return AppResult.ERROR("您未登录",-2);
        }
       // return    AppResult.OK(jsonObject);
    }

    /**
     *
     "payPwd":123456,交易密码11
     "bankCardId":1,提现银行卡ID  1
     "money":200,提现金额  1
     "expenses":4,提现手续费  1
     "expensesrate":2,提现手续费比例  1
     "type":2,提现类型 1开元宝提现 2现金提现 3开元宝营业额提现  1
     "ratio":4,提现税  1
     "taxRatio":2提现税率()  10
     * @return
     */
   @RequestMapping("/Account/cashHandling")
   @ResponseBody
   @Transactional
    public AppResult cashHandling( @ModelAttribute("payPwd")String payPwd,
                                   @ModelAttribute("moneyRate")String moneyRates,
                                    @ModelAttribute("money")String moneys,
                                   @ModelAttribute("expenses")String expensess,
                                   @ModelAttribute("expensesrate")String expensesrates,
                                   @ModelAttribute("type")String types,
                                  @ModelAttribute("ratio")String ratios,
                                   @ModelAttribute("taxRatio")String taxRatios){
       try {
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        BigDecimal money=new BigDecimal(moneys);
        BigDecimal expenses=new BigDecimal(expensess);
        BigDecimal expensesrate=new BigDecimal(expensesrates);
        Integer type=Integer.parseInt(types);
        BigDecimal ratio=new BigDecimal(ratios);
        BigDecimal taxRatio=new BigDecimal(taxRatios);
        BigDecimal moneyRate=new BigDecimal(moneyRates).setScale(4,BigDecimal.ROUND_HALF_UP);
        if (user!=null){
            AppResult json = iAppUserDrwasService.applyRedeem(user.getUserId(),moneyRate, type, money, expenses, expensesrate, taxRatio, ratio,payPwd);
            return 	json;
        }else {
            return AppResult.ERROR("您未登录",-2);
        }
     //   JSONObject json = usersDrawsService.applyRedeem(6237, type, money, fee, expensesrate, taxRatio, bankCardId,dates,payPwd);
      //  return 	AppResult.OK(json);

       }catch (Exception e){
           e.printStackTrace();
           throw new RuntimeException("失败");
       }
    }


    /**
     * 线下转账（ZJF）
     * @param orderNo
     * @param orderImg
     * @param remark
     * @return
     */
    @RequestMapping("/account/offlineSubmit")
    @ResponseBody
    public AppResult offlineSubmit(@ModelAttribute("orderNo")String orderNo,@ModelAttribute("orderImg")String orderImg,@ModelAttribute("remark")String remark){
        Users user = (Users) cacheUtil.get(SessionUtils.getSessionId());
        if (MSGUtil.isBlank(orderImg)&&MSGUtil.isBlank(orderNo)&&MSGUtil.isBlank(remark)){
            return AppResult.ERROR("必填参数不能为空",-1);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("userId",user.getUserId());
        map.put("orderNo",orderNo);
        UsersRecharge usersRecharge=iAppUsersRechargeService.selectUsersRechargeByUserId(map);
        if (MSGUtil.isBlank(usersRecharge)){
            return AppResult.ERROR("订单号有误",-1);
        }
        UsersRecharge usersRecharges = new UsersRecharge();
        usersRecharges.setOrderNo(orderNo);
        usersRecharges.setId(usersRecharge.getId());
        usersRecharges.setOrderImg(orderImg);
        usersRecharges.setStatus(2);
        usersRecharges.setPayType(1);
        if(!"".equals(remark) && remark!=null){
            usersRecharges.setRemark(remark);
        }
        boolean b = iAppUsersRechargeService.updateById(usersRecharges);
        if (b){
            UsersRecharge usersRecharge2=iAppUsersRechargeService.selectUsersRechargeByUserId(map);
            HashMap<String, Object> map1 = new HashMap<>();
            map1.put("orderNo",usersRecharge2.getOrderNo());
            map1.put("payMoney",usersRecharge2.getCash());
            map1.put("createTime",new Date());
            return  AppResult.OK("提交成功",map1);
        }
        return AppResult.ERROR("提交失败",-1);
    }

    /**
     * 获取用户所有赎回猫币
     * @return
     */
    @RequestMapping("/Account/allMaobi")
    @ResponseBody
    public AppResult allMaobi(){
        if(!cacheUtil.isKeyInCache(SessionUtils.getSessionId())){
            return AppResult.ERROR("您还未登陆",-2);
        }
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        Double allMaobi=iAppUserDrwasMaobiService.selectAllMaobiByUserId(user.getUserId());
        Map<String, Object> map = new HashMap<>();
        if (!MSGUtil.isBlank(allMaobi)){
            map.put("allMaobi",allMaobi.toString());
        }else {
            map.put("allMaobi","0.00");
        }
        return AppResult.OK("获取成功",map);
    }

    /*----------------------------------------提现HHTB操作----------------------------------------*/

    /**
     * 提现(数据回显HHTB)
     * @return
     */
    @RequestMapping("/Account/hhtbDraw")
    @ResponseBody
    public AppResult hhtbDraw(){
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        if (user!=null){
            JSONObject jsonObject = iAppUserDrwasService.cashDrawHHTB(user.getUserId());
            return    AppResult.OK(jsonObject);
        }else {
            return AppResult.ERROR("您未登录",-2);
        }
        // return    AppResult.OK(jsonObject);
    }

    /**
     *
     * @param payPwd 交易密码
     * @param moneyRates 汇率
     * @param moneys 提现金额
     * @param expensess 手续费
     * @param expensesrates 手续费比例
     * @param types 提现类型
     * @param ratios 提现税
     * @param taxRatios 提现税率
     * @return
     */
    @RequestMapping("/Account/hhtbHandling")
    @ResponseBody
    @Transactional
    public AppResult DrowsHHTB(@ModelAttribute("payPwd")String payPwd,
                               @ModelAttribute("moneyRate")String moneyRates,
                               @ModelAttribute("money")String moneys,
                               @ModelAttribute("expenses")String expensess,
                               @ModelAttribute("expensesrate")String expensesrates,
                               @ModelAttribute("type")String types,
                               @ModelAttribute("ratio")String ratios,
                               @ModelAttribute("taxRatio")String taxRatios){
        Integer userId=0;
        try {
            Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
            userId=user.getUserId();
            OptBing optBing=new OptBing();
            optBing.setCode("cashHandling");
            optBing.setUid(user.getUserId().toString());
            boolean insert = iOptBingService.insert(optBing);
            if(!insert){
                return AppResult.ERROR("赎回失败请联系工作人员",-1);
            }
            BigDecimal money=new BigDecimal(moneys);
            BigDecimal expenses=new BigDecimal(expensess);
            BigDecimal expensesrate=new BigDecimal(expensesrates);
            Integer type=Integer.parseInt(types);
            BigDecimal ratio=new BigDecimal(ratios);
            BigDecimal taxRatio=new BigDecimal(taxRatios);
            BigDecimal moneyRate=new BigDecimal(moneyRates).setScale(4,BigDecimal.ROUND_HALF_UP);
            if (user!=null){
                AppResult json = iAppUserDrwasService.applyRedeemHHTB(user.getUserId(),moneyRate, type, money, expenses, expensesrate, taxRatio, ratio,payPwd);
                iOptBingService.deleteByCodeAndUid(optBing);
                return json;
            }else {
                iOptBingService.deleteByCodeAndUid(optBing);
                return AppResult.ERROR("您未登录",-2);
            }
        }catch (Exception e){
            //LogInfoManager.appendLog("DrawsLogInfo", "Date:" + new Date() + "  |","用户ID为："+userId+"赎回失败"+"\r\n"+e);
            return AppResult.ERROR("赎回失败请联系工作人员",-1);
        }
    }

    /**
     * 获取用户所有赎回猫币
     * @return
     */
    @RequestMapping("/Account/allhhtb")
    @ResponseBody
    public AppResult allhhtb(){
        if(!cacheUtil.isKeyInCache(SessionUtils.getSessionId())){
            return AppResult.ERROR("您还未登陆",-2);
        }
        Users user =(Users) cacheUtil.get(SessionUtils.getSessionId());
        Double allMaobi=iAppUserDrwasMaobiService.selectAllhhtbByUserId(user.getUserId());
        Map<String, Object> map = new HashMap<>();
        if (!MSGUtil.isBlank(allMaobi)){
            map.put("allMaobi",allMaobi.toString());
        }else {
            map.put("allMaobi","0.00");
        }
        return AppResult.OK("获取成功",map);
    }

}
